import java.io.IOException;
import java.net.*;
import java.util.Scanner;

//Udp的客户端
public class Udpclient {
    private DatagramSocket socket = null;
    private String serverIp;
    private int serverPort;

    public Udpclient(String serverIp, int serverPort) throws SocketException {
        socket = new DatagramSocket();
        this.serverIp = serverIp;
        this.serverPort = serverPort;
    }
    //启动客户端
    public void start() throws IOException {
        Scanner scanner = new Scanner(System.in);
        while (true) {
            //从控制台输入字符串
            System.out.println("->");
            String request = scanner.next();
            //根据UDP协议，构建一个UDP请求，并发送
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),
                    request.getBytes().length, InetAddress.getByName(serverIp), serverPort);
            //InetAddress.getByName()这个是服务器的ip地址
            //serverPort服务器的端口号，操作系统随机分配；
            //发送请求
            socket.send(requestPacket);
            //读取响应，并解析
            DatagramPacket responsePacket = new DatagramPacket(new byte[1024], 1024);
            socket.receive(responsePacket);
            //解析
            String response = new String(responsePacket.getData(), 0, responsePacket.getLength(), "UTF-8");
            //将响应结果显示到显示屏上
            System.out.printf("req: %s, resp: %s\n", request, response);
        }
    }
    public static void main(String[] args) throws IOException {
        Udpclient udpClient = new Udpclient("127.0.0.1", 9090);
        udpClient.start();
    }
}

